class TemplateError extends Error{
    constructor(lineIndex,message){
        super(message)
        this.lineIndex=lineIndex
    }
}

class TemplateEngine {
    constructor(arr, view) {
        this.arr = arr
        this.view = view
        this.p = 'AZEDCHJ'
        this.dataName = 'KBYGVIO'
        this.logMethodName = 'VHUIJMF'
        this.flagRegex = /\$\{(.+?)\}/g;
    }
    initSystemVarible() {
        //添加系统自带变量
        let obj = {
            Array() {
                return []
            },
            Range(a, b) {
                if (b === undefined) {
                    let arr = []
                    for (let i = 0; i < a; i++) {
                        arr.push(i)
                    }
                    return arr
                } else {
                    if (b < a) {
                        throw new Error("Range的第二个参数必须<=第一个")
                    }
                    let arr = []
                    for (let i = a; i <= b; i++) {
                        arr.push(i)
                    }
                    return arr
                }

            },
            Map(key, value) {
                if (key !== undefined) {
                    let res = {}
                    res[key] = value
                    return res
                }
                return {}
            }
        }
        this.view = Object.assign(obj, this.view)
    }
    initVarible(arr_ZWDGHUIJK, view, dataName) {
        //添加用户自定义变量
        for (let key in view) {
            arr_ZWDGHUIJK.push(`let {${key}} = ${dataName}`)
        }
    }
    replaceMoreSpaceToOneSpace(str) {
        // 使用正则表达式进行替换
        return str.replace(/'[^']*'|\s+/g, function (match) {
            // 如果匹配到的是单引号内的内容，直接返回原文
            if (match[0] === "'") {
                return match;
            }
            // 否则，替换连续多个空格为一个空格
            return ' ';
        });
    }
    translate(res, arr) {
        let p = this.p
        arr.forEach((line, lineIndex) => {
            let trimedLine = line.trim()
            if (trimedLine.startsWith("#dim ")) {
                let vars = trimedLine.substring(5)
                res.push("let " + vars)
            } else if (trimedLine.startsWith("#set ")) {
                let str = trimedLine.substring(5)
                res.push(str)
            } else if (trimedLine.startsWith("#set ")) {
                let str = trimedLine.substring(5)
                res.push(str)
            } else if (trimedLine.startsWith("#for ")) {
                let options = this.replaceMoreSpaceToOneSpace(trimedLine).split(' ')
                if (options.length != 4) {
                    throw new TemplateError(lineIndex,"For的语法不对，For循环应该由4段组成，而不是" + options.length)
                }
                //解析for的key和value
                let i1 = options[1].split(',')
                let keyName, valueName, collectionName
                if (i1.length === 1) {
                    keyName = "key"
                    valueName = i1[0]
                } else if (i1.length === 2) {
                    keyName = i1[0]
                    valueName = i1[1]
                } else {
                    throw new TemplateError(lineIndex,"For的语法不对，接受字段数量不应该为" + i1.length)
                }
                //遍历的对象名
                collectionName = options[3]
                let str = `for(let ${keyName} in ${collectionName}){`
                let str2 = `let ${valueName}=${collectionName}[${keyName}]`
                res.push(str)
                res.push(str2)
            } else if (trimedLine == "#end for") {
                res.push("}")
            } else if (trimedLine.startsWith("#if ")) {
                let vars = trimedLine.substring(4)
                res.push(`if(${vars}){`)
            } else if (trimedLine.startsWith("#else if ")) {
                let vars = trimedLine.substring(8)
                res.push(`}else if(${vars}){`)
            } else if (trimedLine === "#else") {
                res.push(`}else {`)
            } else if (trimedLine === "#end if") {
                res.push(`}`)
            } else if (trimedLine.startsWith("#log ")) {
                let vars = trimedLine.substring(5)
                res.push(`${this.logMethodName}(${lineIndex + 1},\`${vars}\`)`)
            } else if (trimedLine.startsWith("##")) {
                //注释行，忽略
            } else if (trimedLine.startsWith("#")) {
                //调用方法
                let vars = trimedLine.substring(1)
                res.push(`${vars}`)
            } else {
                res.push(`${p}(\`${line}\`)`)
                // res.push(`${p}(\`${trimedLine}\`)`)
            }

        })
    }
    render() {
        //将每行转成js代码
        let jsCode = []
        this.initSystemVarible()
        this.initVarible(jsCode, this.view, this.dataName)
        this.translate(jsCode, this.arr)
        let logs=[]
        let res=this.exec.call(undefined, jsCode, this.view,logs)
        return {
            logs,
            res
        }
    }
    /**
     * 
     * @param {Array} ARR_JNBGYUIO 解析后的JavaScript代码 
     * @param {*} view_BGPKNVF 用户自定义view
     */
    exec(ARR_JNBGYUIO, view_BGPKNVF,LOGS_OKMNBGV) {
        console.log(ARR_JNBGYUIO)
        const KBYGVIO = view_BGPKNVF
        //解析后的模板
        const RES_NKIJHGB = []
        //解析模板的回调
        const AZEDCHJ = function (line) {
            RES_NKIJHGB.push(line)
        }
        //#log指令日志
        const VHUIJMF = function (lineIndex, str,leave) {
            LOGS_OKMNBGV.push({
                line:lineIndex,
                str,
                leave:leave
            })
        }
        try {
            //执行脚本
            eval(ARR_JNBGYUIO.join("\n"))
        } catch (e) {
            //throw new Error(e.message)
            VHUIJMF(e.lineIndex,e.message,"error")
        }
        console.log(RES_NKIJHGB)
        return RES_NKIJHGB.join("\n")
    }

}

class StringTemplate {
    constructor(templateString) {
        this.arr = templateString.split('\n')
    }
    render(data) {
        return new TemplateEngine(this.arr, data).render()
    }
}
export default StringTemplate